//
//  LSAlipay.m
//  HappyStore
//
//  Created by 陈锋 on 16/8/12.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "LSAlipay.h"

@implementation LSAlipay

+(NSString *)alipay:(NSString *)subject body:(NSString *)body price:(double)price{

    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *partner = @"2088121871507059";
    NSString *seller = @"2022696266@qq.com";
    NSString *privateKey =@"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ7B43Un4RDGOI90iis9X92TJ26RrA1Yz0w1vu+ZKtdU2Qq/+AYQXidGCPh+Bdpk0zwXnsl/Re2hysk4NO3OXZkSmH9OwszpjP+7HzKVwAZ0q0psor+IotuYOELrlKX9FteQdwhOobh6g156ohDET66Lg42GGG90wjWENHI2WbYxAgMBAAECgYAC1szOh4wK1MCmMBtYcpyIRd1qqMg+5NuwLTXg6whNGYNYId65nQlSAnqelwJbyXnNlU6No+0INuB9gLfRmOMrlmeNORvAOZuQnZjFL0peHCBLF2nG1MT3FjIUspjAVdGbIraihIiwFCpZpWSvtmBbbHh0a+m/EF9GFdVhOdzoAQJBAMvOWBwCykBGE/WffbK7wV7C9WByYsEzBIOyig5aFu2GVW1EFCPRE+dJJ3yWvoatJgm69CKksSS+2Tl1t+ifoSECQQDHaiAQdlOe1pljVuhsSdyRc2yzwOjkUGrsE4Gr++JgZXzTTcUq/RGaj3GWb467b3baDk1LY129l1stJ8eTKKMRAkEAr3nTfRKd5ycvSj1vcbOc86Uytj7mbmgpy+auXVsOAKa36OND3+7Fj076M5hrJPPyG1CfoTBh4Tx9Na74kM7YYQJAPWEA9ZA2NNHA7L63U314kpyAfOOHy56lCn0GkLU6/IjAXxm08oJqhLRaNf+oYzDv2DZGvEmddNm9iqyP1U/QwQJBALYuA1d9w8GhRD0cvzqdbphF20+Pot8BVQ6u43gu+9a/EX3mx5EzVnWP3LACDSfS2zer0b5oCN9mTn28Fy8LNwY=";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return nil;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.sellerID = seller;
    NSString * outTradeNO = [LSAlipay generateTradeNO]; //订单ID（由商家自行制定）
    
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYYMMddhhmmss"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    
    order.outTradeNO = [NSString stringWithFormat:@"%@%@",dateString,outTradeNO];
    
    order.subject = subject; //商品标题
    order.body = body; //商品描述
    
    //    if (self.moneyLabel) {
    //        price = [self.moneyLabel.text floatValue];
    //    }
    order.totalFee = [NSString stringWithFormat:@"%.2f",price]; //商品价格
    order.notifyURL =  @"http://www.lensum.com/alipay/notify_url.jsp"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showURL = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"aliPayHappyStore";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    //    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            //            NSLog(@"reslut = %@",resultDic);
            NSString *resultStatus = [resultDic valueForKey:@"resultStatus"];
            if ([resultStatus isEqualToString:@"9000"]) {
                
                NSLog(@"status:9000");
                
            } else if ([resultStatus isEqualToString:@"6001"]){
                NSLog(@"status:6001");
            }
        }];

    }
    

    return order.outTradeNO;
}

+ (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}
@end
